from fastapi import FastAPI, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from fastapi.responses import JSONResponse
from contextlib import asynccontextmanager
import uvicorn
import os
from config import settings
from database import init_db
from routers import auth, wechat, user, contests, search, upload

# 应用生命周期管理
@asynccontextmanager
async def lifespan(app: FastAPI):
    """
    应用生命周期管理
    在应用启动时初始化数据库，关闭时清理资源
    """
    # 启动时执行
    print("正在启动 AI HUB API 服务...")
    
    # 初始化数据库
    try:
        init_db()
        print("数据库初始化完成")
    except Exception as e:
        print(f"数据库初始化失败: {e}")
    
    # 确保上传目录存在
    os.makedirs(settings.upload_dir, exist_ok=True)
    print(f"上传目录已准备: {settings.upload_dir}")
    
    yield
    
    # 关闭时执行
    print("AI HUB API 服务正在关闭...")

# 创建FastAPI应用实例
app = FastAPI(
    title="AI HUB API",
    description="AI HUB 前后端接口服务",
    version="1.0.0",
    docs_url="/docs" if settings.debug else None,
    redoc_url="/redoc" if settings.debug else None,
    lifespan=lifespan
)

# 配置CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.cors_origins,
    allow_credentials=True,
    allow_methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"],
    allow_headers=["*"],
)

# 静态文件服务（用于提供上传的文件）
if os.path.exists(settings.upload_dir):
    app.mount("/uploads", StaticFiles(directory=settings.upload_dir), name="uploads")

# 全局异常处理器
@app.exception_handler(HTTPException)
async def http_exception_handler(request: Request, exc: HTTPException):
    """
    HTTP异常处理器
    统一处理HTTP异常，返回标准格式的错误响应
    """
    return JSONResponse(
        status_code=exc.status_code,
        content={
            "code": exc.status_code,
            "message": exc.detail,
            "data": None
        }
    )

@app.exception_handler(Exception)
async def general_exception_handler(request: Request, exc: Exception):
    """
    通用异常处理器
    处理未捕获的异常，避免服务器错误暴露给客户端
    """
    if settings.debug:
        # 开发环境下显示详细错误信息
        error_detail = str(exc)
    else:
        # 生产环境下隐藏错误详情
        error_detail = "服务器内部错误"
    
    return JSONResponse(
        status_code=500,
        content={
            "code": 500,
            "message": error_detail,
            "data": None
        }
    )

# 注册路由
app.include_router(auth.router)
app.include_router(wechat.router)
app.include_router(user.router)
app.include_router(contests.router)
app.include_router(search.router)
app.include_router(upload.router)

# 根路径
@app.get("/")
async def root():
    """
    根路径接口
    返回API基本信息
    """
    return {
        "code": 200,
        "message": "AI HUB API 服务运行正常",
        "data": {
            "name": "AI HUB API",
            "version": "1.0.0",
            "environment": settings.environment,
            "docs_url": "/docs" if settings.debug else None
        }
    }

# 健康检查接口
@app.get("/health")
async def health_check():
    """
    健康检查接口
    用于监控服务状态
    """
    return {
        "code": 200,
        "message": "服务健康",
        "data": {
            "status": "healthy",
            "timestamp": "2024-01-16T00:00:00Z"
        }
    }

# API信息接口
@app.get("/api/info")
async def api_info():
    """
    API信息接口
    返回API的详细信息和配置
    """
    return {
        "code": 200,
        "message": "success",
        "data": {
            "name": "AI HUB API",
            "version": "1.0.0",
            "description": "AI HUB 前后端接口服务",
            "environment": settings.environment,
            "debug": settings.debug,
            "upload_limits": {
                "max_file_size": settings.max_file_size,
                "allowed_image_types": settings.allowed_image_types.split(","),
                "allowed_video_types": settings.allowed_video_types.split(","),
                "allowed_audio_types": settings.allowed_audio_types.split(",")
            },
            "features": [
                "用户认证",
                "微信登录",
                "作品管理",
                "竞赛信息",
                "AI工具搜索",
                "文件上传"
            ]
        }
    }

# 中间件：请求日志
@app.middleware("http")
async def log_requests(request: Request, call_next):
    """
    请求日志中间件
    记录所有HTTP请求的基本信息
    """
    import time
    
    start_time = time.time()
    
    # 处理请求
    response = await call_next(request)
    
    # 计算处理时间
    process_time = time.time() - start_time
    
    # 在开发环境下打印请求日志
    if settings.debug:
        print(f"{request.method} {request.url.path} - {response.status_code} - {process_time:.3f}s")
    
    # 添加处理时间到响应头
    response.headers["X-Process-Time"] = str(process_time)
    
    return response

if __name__ == "__main__":
    # 直接运行时启动服务器
    uvicorn.run(
        "main:app",
        host=settings.host,
        port=settings.port,
        reload=settings.debug,
        log_level="info" if settings.debug else "warning"
    )